package com.mall.user.services;

import com.mall.commons.tool.exception.ValidateException;
import com.mall.user.IRegisterService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.entitys.UserVerify;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dal.persistence.UserVerifyMapper;
import com.mall.user.dto.UserRegisterRequest;
import com.mall.user.dto.UserRegisterResponse;
import com.mall.user.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author
 * @date 2020/12/19 16:19
 */
@Component
@Service
@Slf4j
public class RegisterServiceImpl implements IRegisterService {
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private UserVerifyMapper userVerifyMapper;
    @Autowired
    JavaMailSender mailSender;

    /**
     * 用户注册接口
     *
     * @param registerRequest
     */
    @Override
    public UserRegisterResponse register(UserRegisterRequest registerRequest) {
        UserRegisterResponse response = new UserRegisterResponse();
        //1.插入用户信息进入用户表
        //验证传入的信息是否为空
        registerRequest.requestCheck();
        //验证用户信息是否重复
        try {
            verifyUserNameIsDuplicate(registerRequest);
        } catch (Exception e) {
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }
        //向表中插入用户信息
        Member member = new Member();
        member.setUsername(registerRequest.getUserName());
        String password = DigestUtils.md5DigestAsHex(registerRequest.getUserPwd().getBytes());
        member.setEmail(registerRequest.getEmail());
        member.setPassword(password);
        member.setUpdated(new Date());
        member.setCreated(new Date());
        member.setIsVerified("N");
        member.setState(1);
        //插入数据库失败则返回异常信息
        try {
            memberMapper.insert(member);
        } catch (Exception e) {
            response.setCode(SysRetCodeConstants.USER_REGISTER_FAILED.getCode());
            response.setMsg(SysRetCodeConstants.USER_REGISTER_FAILED.getMessage());
            return response;
        }
        //2.插入用户验证消息进入用户验证表
        UserVerify userVerify = new UserVerify();
        userVerify.setUsername(registerRequest.getUserName());
        String key = registerRequest.getUserName() + registerRequest.getUserPwd() + UUID.randomUUID();
        String uuid = DigestUtils.md5DigestAsHex(key.getBytes());
        userVerify.setUuid(uuid);
        userVerify.setRegisterDate(new Date());
        userVerify.setIsExpire("N");
        userVerify.setIsVerify("N");
        int effRow2 = userVerifyMapper.insert(userVerify);
        //插入验证信息进入数据库失败则返回异常信息
        if (effRow2 != 1) {
            response.setCode(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getCode());
            response.setMsg(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getMessage());
            return response;
        }
        //3.发送激活邮件
        //TODO  后续需要用消息队列优化
        new Thread(new Runnable() {
            @Override
            public void run() {
                sendEmail(uuid,registerRequest);
            }
        }).start();


        log.info("用户注册成功,参数为:{}",registerRequest);
        response.setCode(SysRetCodeConstants.SUCCESS.getCode());
        response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        return response;
    }

    /**
     * 发送用户激活邮件
     * @param uuid
     * @param registerRequest
     */
    private void sendEmail(String uuid, UserRegisterRequest registerRequest) {
        SimpleMailMessage message = new SimpleMailMessage();
        //TODO 可以将需要的字符定义在配置文件中
        message.setSubject("CSMALL用户激活");
        message.setFrom("yuankai0425@163.com");
        message.setTo(registerRequest.getEmail());
        //http://localhost:8080?uid=xxx&username=xxx
        StringBuilder stringBuilder = new StringBuilder();
//        stringBuilder.append("http://localhost:8080/user/verify?uid=")
//        stringBuilder.append("http://192.168.6.33:8080/user/verify?uid=")
        stringBuilder.append("http://127.0.0.1:8080/user/verify?uid=")
                .append(uuid)
                .append("&username=")
                .append(registerRequest.getUserName());
        message.setText(stringBuilder.toString());
        mailSender.send(message);

    }

    //判断用户信息是否为空
    private void verifyUserNameIsDuplicate(UserRegisterRequest registerRequest) {
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username",registerRequest.getUserName());
        List<Member> members = memberMapper.selectByExample(example);
        //不为空则抛出异常 由自定义异常接收
        if (!CollectionUtils.isEmpty(members)) {
            throw new ValidateException(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getCode(),SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getMessage());
        }
    }
}
